from django.conf import settings
if settings.DATABASE_TYPE == 'mysql':
    from tanxi.models.mysql.mysql_user_model import UserModel, UserManager 
    from tanxi.models.mysql.mysql_article_model import ArticleModel
        
elif settings.DATABASE_TYPE == 'sqlite':
    from tanxi.models.sqlite.sqlite_user_model import SqliteUserModel as UserModel
    from tanxi.models.sqlite.sqlite_user_model import SqliteUserManager as UserManager
    from tanxi.models.sqlite.sqlite_article_model import SqliteArticleModel as ArticleModel
else:
    raise ValueError("Unsupported database type specified in settings.")

# mysql DATABASES
# log
from ...Handler.Logger import log_error,log_info
# 密码加密
from django.contrib.auth.hashers import check_password
from django.contrib.auth.hashers import make_password


class UserHandler:
    def __init__(self):
        pass

    # 用户登录时  用户注册只需提供 username password  user_id自增
    def user_login(self, username, password, email=None):
        # 检查用户名和密码是否提供
        data = None
        if not username or not password:
            log_error(f"用户名密码 {username},{password}")
            raise ValueError('用户名或密码为空')
        try:
            user = UserModel.objects.get(username=username)
            
            log_info(f"用户登录: {user.password}, {password}")

            # 使用 check_password 验证密码
            if check_password(password, user.password):
                # 登录成功
                data = {"user_id":user.user_id,
                        "login_message":"login_success",
                        "token":111}
            else:
                data = {"user_id":user.user_id,
                        "login_message":"login_failed",
                        # "token":111
                        }
            
            return data
        except UserModel.DoesNotExist:
            # 没有用户 注册
            # 在注册时应使用 make_password 加密密码
            encrypted_password = make_password(password)
            new_user = UserModel.objects.create(username=username, password=encrypted_password, email=email)
            data = {"user_id":new_user.user_id,
                    "login_message":"registration_success",
                    "token":111
                    }
            return data
    

    def update_user_info(self, data=None):
        if data is None:
            raise ValueError("用户信息不能为空")

        user_id = data.get('user_id')
        if not user_id:
            # 未传入用户user_id
            raise ValueError("用户user_id不能为空")
        try:
            # 获取用户
            user = UserModel.objects.get(user_id=user_id)

        except UserModel.DoesNotExist:
            log_error(f"用户不存在: {user_id}")
            return False
        
        # 存在情况更新用户信息
        for key, value in data.items():
            if key == 'password':  # 单独处理密码字段
                user.set_password(value)  # 使用 Django 的密码加密方法
            else:
                setattr(user, key, value)

        user.save()  # 保存更新
        # 更新成功标志
        return True

    # 用户信息获取
    # 根据参数获取和获取所有用户
    def get_user_info(self, user_id=None):
        if user_id is None:
            users = UserModel.objects.all()
            user_data = [
                {
                    'username': user.username,
                    'password': user.password,
                    'user_id': user.user_id,
                    'name': user.name,
                    'address': user.address,
                    'phone': user.phone,
                    'email': user.email,
                    # 添加其他需要返回的用户信息字段
                }
                for user in users
            ]
        else:
            user = UserModel.objects.get(user_id=user_id)
            # 获取此user_id第一个
            # user = UserModel.objects.filter(user_id=user_id).first()
            user_data = {
                'username': user.username,
                'password': user.password,
                'user_id': user.user_id,
                'name': user.name,
                'address': user.address,
                'phone': user.phone,
                'email': user.email,
                # 添加其他需要返回的用户信息字段
            }

        return user_data
    

    def delete_user(self, user_id):
        """根据用户user_id 删除用户"""
        try:
            user = UserModel.objects.get(user_id=user_id)
            user.delete()
            return True
        except UserModel.DoesNotExist:
            return False